<template>
    <el-container class="bodys">
        <el-card class="register-card">
            <el-form ref="register" :model="register" :rules="registerRules"
                label-width="80px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="register.name" placeholder="请输入真实姓名"/>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="register.gender">
                        <el-radio :label="0">女</el-radio>
                        <el-radio :label="1">男</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="身份证号" prop="idCard">
                    <el-input v-model="register.idCard" placeholder="请输入身份证号" />
                </el-form-item>
                <el-row :gutter="10">
                    <el-col :span="15">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="register.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" 
                            size="small" 
                            @click="showImageCode" 
                            :disabled="getSmsCodeFlag">
                            {{ buttonText }}
                        </el-button>
                    </el-col>   
                </el-row>
                <el-form-item label="验证码" prop="smsCode">
                    <el-input v-model="register.smsCode" placeholder="请输入短信验证码"/>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="register.password" placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="register.address" placeholder="请输入地址"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="register.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item >
                    <el-button type="primary" size="small" @click="register1">注册</el-button>
                    <el-button type="primary" size="small" @click="resetregister">取 消</el-button>
                </el-form-item>
                <el-form-item>
                    <span style="color:#999;margin-top:-20px">已有账户？  </span>
                    <el-button type="text" @click="toLogin" >去登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-dialog
            title="请输入图片验证码"
            :visible.sync="showCodeFlag"
            :close-on-click-modal="false"
            width="400px"
            :center="true">
            <el-form 
                :rules="{code:[{required:true,message:'请输入图片验证码'}]}" 
                :model="imageCode" 
                ref="imageCode"
                label-width="30%">
                <el-row :gutter="10">
                    <el-col :span="15">
                        <el-form-item label="验证码" prop="code">
                            <el-input v-model="imageCode.code" placeholder="请输入图片验证码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <img :src="imageCode.codeUrl" @click="getCode"/>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button type="primary" size="small" @click="getSmsCode">确定</el-button>
                    <el-button type="primary" size="small" @click="cancleGetSmsCode">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </el-container>
</template>

<script>
    import { getCode, register, checkCode} from "../api/user"
    export default {
        
        data() {
            return {
                getSmsCodeFlag: false, // 按钮禁用状态
                buttonText: '点击获取验证码', // 按钮文本
                imageCode:{
                    uuid:'',
                    code:'',
                    codeUrl:'',//图片验证码的Base64编码
                },
                countdown: 60 ,// 倒计时时长（秒）
                showCodeFlag:false,
                register:{
                    name:'',
                    gender:'',
                    idCard:'',
                    phone:'',
                    password:'',
                    address:'',
                    email:'',
                    smsCode:'',
                },
                registerRules:{
                    name:[{required:true,message:'请输入姓名'},
                        {min:2,max:5,message:'姓名最少2位最多5位'}],
                    gender:[{required:true,message:'请选择性别'}],
                    password:[{required:true,message:'请输入密码'},
                        {min:8,max:15,message:'密码最少8位最多15位'}],
                    smsCode:[{required:true,message:'请输入验证码'},
                        { pattern: /^[1-9]\d{5}$/, message: '只能是6位整数' }],
                    phone:[{required:true,message:'请输入手机号'},
                        { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入正确的手机号' }],
                    idCard:[{required:true,message:'请输入身份证号'},
                    { pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/, message: '请输入正确的身份证号' }],
                    address:[{required:true,message:'请输入地址'}],
                    email:[{required:false,pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱' },],
                },
            }
        },
        methods: {
            toLogin(){
                this.$router.push({
                    path:'/login'
                })
            },
            showImageCode(){
                this.$refs.register.validateField("phone",error=>{
                    if(error){
                        this.$message.warning("请先输入手机号")
                    }else{
                        this.showCodeFlag = true
                    }
                })
            },
            async getCode(){
                const {data:{uuid,codeUrl}} = await getCode()
                this.imageCode.uuid = uuid
                this.imageCode.codeUrl = codeUrl
            },
            getSmsCode() {
                // 点击按钮后执行的操作
                this.$refs.imageCode.validate(async valid =>{
                    if(valid){
                        await checkCode(this.imageCode.uuid,this.imageCode.code,this.register.phone).then(resp=>{
                            if(resp.code==200){
                                this.startCountdown(); // 启动倒计时
                                this.$message.success("发送成功")
                            }else{
                                this.$message.error(resp.message)
                            }
                        })
                    }
                })
                this.showCodeFlag = false
            },
            startCountdown() {
                this.getSmsCodeFlag = true; //禁用按钮
                let timer = setInterval(() => {
                    if (this.countdown > 0) {
                        this.buttonText = this.countdown--;
                    } else {
                        this.getSmsCodeFlag = false; // 倒计时结束，启用按钮
                        this.buttonText = '点击获取验证码'; // 恢复按钮文本
                        clearInterval(timer);
                    }
                }, 1000);
            },
            register1(){
                this.$refs.register.validate(async valid =>{
                    if(valid){
                        const { code, message, data } = await register(this.register)
                        if(code === 200){
                            sessionStorage.removeItem('token')//如果用户同时注册多个用户
                            sessionStorage.setItem('token',data.token)
                            this.resetregister()
                            this.$router.push('/')
                        }else{
                            this.$message.error(message)
                        }
                    }else{
                        return false
                    }
                })
            },
            resetregister(){
                this.$refs.register.resetFields();
                this.imageCode.uuid = ''
                this.getCode()
            },
            cancleGetSmsCode(){
                this.$refs.imageCode.resetFields();
                this.showCodeFlag = false
                this.imageCode.uuid = ''
                this.getCode()
            }, 
        },
        mounted() {
            this.getCode()
        },
    }
</script>

<style scoped>
    .el-container{
        width: 100vw;
        height: 100vh;
        background: url('../assets/bg1.jpeg') no-repeat;
        background-size: 100vw 100vh;
        background-attachment: fixed;
    }
    .register-card {
        width: 400px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(255, 255, 255, 0.7);
        padding: 20px;
    }
</style>